package cn.tedu.controller;

import cn.tedu.constant.WxUrlConstant;
import cn.tedu.service.IWx2311Service;
import cn.tedu.util.HttpClientUtil;
import cn.tedu.util.XmlUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx2311")
public class Wx2311Controller {


    @Autowired
    private IWx2311Service wx2311Service;

    @Value("${wx.appID}")
    private String appId;

    @Value("${wx.appsecret}")
    private String secret;

    @RequestMapping("/getCode")
    public String getCode(@RequestParam("code") String code, @RequestParam("state") String state
            , HttpServletRequest request, HttpServletResponse response){

        // 通过这个code 去拿到Access_token 这个Access_token 跟之前那个不一样
        String url = WxUrlConstant.USER_INFO_CODE_ACCESS_TOKEN.replace("APPID",appId)
                .replace("SECRET",secret).replace("CODE",code);
        String s = HttpClientUtil.doGet(url);

        HashMap hashMap = JSON.parseObject(s, HashMap.class);
        Object openid = hashMap.get("openid");
        String openId ="";
        if(openid instanceof String){
            openId  = (String)openid;
        }
        // 这个地方得access_token和之前得可不一样
        String userInfoUrl = WxUrlConstant.USER_INFO.replace("OPENID",openId)
                .replace("ACCESS_TOKEN",(String)hashMap.get("access_token"));
        System.out.println(s);
        // 通过access_token获取用户基本信息存储到刚刚的关注用户表里面  - 存到新的数据行设置状态为未关注
        String s1 = HttpClientUtil.doGet(userInfoUrl);
        // 把获取到的用户信息存入数据库 亦或者可以准备一个jwtUtil.genToken();
        System.out.println(s1);
        try {
            // 如果需要携带参数, 则使用路径拼接得方法  前端js也是可以获取url上面得参数得http://www.baidu.com?token=jwtToken
            response.sendRedirect("http://xxluckey.cn");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    @GetMapping("/createMenu")
    public String createMenus(){
        return  wx2311Service.createMenu();
    }




    @GetMapping("/getAccessToken")
    public String getAccessToken(){
       return wx2311Service.getAccessToken();
    }



    @GetMapping
    public String checkWx(String signature , String timestamp
            ,String nonce,String echostr){
        boolean flag = wx2311Service.checkWx(signature,timestamp,nonce,echostr);
        if(flag){
            return echostr;
        }
        return null;
    }

    @PostMapping
    public String sendMessage(@RequestBody String message) throws Exception {
        //  文本消息，语音消息，视频消息，点击事件 关注事件
        Map<String, Object> stringObjectMap = XmlUtils.xmlStrToMap(message);
        System.out.println(stringObjectMap);
        return message;
    }


}
